package com.chat.business.service.impl;

import com.chat.business.service.IFileService;
import com.chat.common.vo.R;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author wei kunJie
 * @date 2024/5/24 14:55:29
 */
@Service
public class FileServiceImpl implements IFileService {

    @Value(("${file-save-path}"))
    private String fileSavePath;

    @Override
    public R<String> uploadImage(MultipartFile file, HttpServletRequest request) {
        if (file == null)
            return R.failed("上传文件不能为空");
        String fn = file.getOriginalFilename();
        if (fn == null)
            return R.failed("文件名为空");
        if (!(fn.endsWith(".png") || fn.endsWith(".jpg")))
            return R.failed("图片只能是jpg或png格式");
        //文件保存目录
        //如果目录不存在，则创建
        File dir = new File(fileSavePath + "EChartFile\\");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //文件后缀
        String suffix = fn.substring(file.getOriginalFilename().lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
        File newFile = new File(fileSavePath + "EChartFile\\" + newFileName);
        //复制操作
        try {
            file.transferTo(newFile);
            //协议 :// ip地址 ：端口号 / 文件目录(/fileType/userId/xxx.nii)
            String url = request.getScheme() + "://" + "easychat.service.com" + ":" + request.getServerPort() + "/EChartFile/" + newFileName;
            return R.succeed("上传成功", url);
        } catch (IOException e) {
            e.printStackTrace();
            return R.succeed("服务器IO错误");
        }
    }
}
